/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package main;

import java.io.IOException;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

/**
 *
 * @author Administrator
 */
public class BacayScene extends CardGameScene implements IGameDisplay {

    private static final int TIME_FOR_THINK = 30;
    private boolean isDrawResult;
    private boolean isBeginGame;
//    private boolean isViewer;
    private boolean isJoined;
    private int numberCardShared;
    private int numberCardReceive;
    private int numberCardNotOpen;
    private int cardMoveIndex;
    private int[] resultOrder;
    private Card[][] cardInHand;
    private Card[] cardMoves;
    private Image cardImages;
    private Image winImage;
    private Image loseImage;
    private String[] rs3Data;
    private String[] s3cData;
    private int[] cardInHandId;
    private int[] cardInHandIndex;
    private int[] cardSharePos;
    private int startOpen;
    private int countOpen;
    private boolean isDrawClock;
    private Image boxCenterTable;

    public BacayScene(MainCanvas parent) {
        super(parent);
        initValue();
        initObject();
        if (gameData.cardInHandId != null && !isViewer) {
            setCardShare(gameData.cardInHandId);
        } else {
            initForView();
        }
    }

    private void initForView() {
        cardHeight = cardImages.getHeight();
        cardWidth = cardImages.getWidth() / 53;
        isShowJoin = true;

    }

    private void initValue() {
        playerId = gameData.getPlayerId();
        numberPlayers = gameData.getNumberPlayers();
        maxPlayer = gameData.getMaxPlayer();
        numberCardNotOpen = 3;
        gameData.setGameDisplay(this);
        isViewer = (gameData.getMyViewId() < maxPlayer ? false : true);
        if (isViewer) {
            playerId = 0;
        }
    }

    private void initObject() {
        try {
            cardInHand = new Card[4][3];
            cardInHandIndex = new int[4];
            cardMoves = new Card[12];
            resultOrder = new int[4];
            boxCenterTable = Utils.loadImage("o_dem_nguoc.png");
            winImage = Utils.loadImage("thang.png");
            loseImage = Utils.loadImage("thua.png");
            cardImages = library.getCardImage();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public void dispose() {
        resultOrder = null;
        cardInHand = null;
        cardMoves = null;
        cardImages = null;
        winImage = null;
        loseImage = null;
        rs3Data = null;
        s3cData = null;
        cardInHandId = null;
        cardInHandIndex = null;
        if (isGoBack) {
            gameData.disposeBacayData();
        }
        super.dispose();
    }

    private void processData(String[] message) {
        for (int i = 0; i < message.length; i++) {
            Debug.d("rs3 message :" + message[i]);
        }
        if (message[0].equals("RS3")) {
            for (int i = 1; i < message.length - 1; i++) {
                int id = Integer.parseInt(message[i]);
                int result = Integer.parseInt(message[i + 1]);
                Debug.d("id :" + id + ", result :" + result);
                resultOrder[id] = result;
                i += 2;
            }
        }
        for (int i = 0; i < numberPlayers; i++) {
            Debug.d("result " + i + ":" + resultOrder[i]);
        }
        isFinishGame = true;
    }
    //------------------------------------------------------------------------

    protected void doWhenTimeExpired() {
        if (timeForThink == 0) {
            isDrawClock = false;
            for (int j = 0; j < maxPlayer; j++) {
                if (gameData.isPlays[j]) {
                    int posId = (j - playerId + maxPlayer) % maxPlayer;
                    for (int i = 0; i < 3; i++) {
                        Card card = cardInHand[posId][i];
                        card.openCard();
                        card.setPosition(getDestinationX(posId) + DISTANCE_HORIZONTAL_CARD * i, getDestinationY(posId));
                    }
                    Request.finishOpenCardBaCay();
                    parent.repaint();
                }

            }
        }
    }

    void doCardGameLoop() {
        if (cardMoveIndex > 0) {
            moveShareCard();
        }
    }

    protected void doSubMenu() {
        switch (subMenu.getSelectedIndex()) {
            case 0:
                if (isBeginGame || isFinishGame || isViewer) {
                    super.doSubMenu();
                }
                break;
            case 1:
                //loa
                isShowSubMenu = false;
                isShowSpeaker = true;
                speakerBox.setText("");
                parent.repaint();
                break;
        }
    }

    private void moveShareCard() {
        cardMoves[numberCardShared].move();
        parent.repaint();
        if (cardMoves[numberCardShared].getState() == Card.STATE_NORMAL) {
            int posId = cardSharePos[numberCardShared % numberPlayers];
            Debug.d("pos id :" + posId);
            Card card = cardMoves[numberCardShared];
            int index = numberCardShared / numberPlayers;
//            if (posId != 0) {
//                card.openCard();
//            }
            cardInHand[posId][index] = card;
            if (posId != 0 || isViewer) {
                cardInHand[posId][index].setPosition(card.getX() + DISTANCE_HORIZONTAL_CARD * index, card.getY());
            }
            cardInHandIndex[posId]++;
            parent.repaint();
            numberCardShared++;
            if (cardMoveIndex == numberCardShared) {
                isBeginGame = true;
                isDrawClock = true;
                timeForThink = TIME_FOR_THINK;
                cardMoveIndex = 0;
                if (isViewer) {
//                    isFinishGame = true;
                    parent.repaint();
                }
            }
        }
    }
//-------------------------------------------------------------------------------

    protected void paintCardGame(Graphics g) {
        paintClock(g);
        paintCardInHand(g);
        if (cardMoveIndex > 0) {
            paintCardMove(g);
        }
        paintPlayer(g);
        paintBarMenu(g);
    }

    private void paintClock(Graphics g) {
        if (isDrawClock) {
            g.drawImage(boxCenterTable, canvasWidth / 2 - boxCenterTable.getWidth() / 2, canvasHeight / 2 - boxCenterTable.getHeight() / 2, 0);
            PiPoDesigner.drawCenterString(g, String.valueOf(timeForThink), PiPoDesigner.COLOR_BLACK, PiPoDesigner.COLOR_WHITE, canvasWidth / 2, canvasHeight / 2 - 8);
        } else {
//            PiPoDesigner.drawCenterString(g, "Xin chờ...", PiPoDesigner.COLOR_BLACK, PiPoDesigner.COLOR_WHITE, canvasWidth / 2, canvasHeight / 2 - 8);
        }
    }

    private void paintCardMove(Graphics g) {
        for (int i = numberCardShared; i < cardMoveIndex; i++) {
            cardMoves[i].paint(g);
        }
    }

    private void paintPlayer(Graphics g) {
        for (int i = 0; i < maxPlayer; i++) {
            if (gameData.isPlays[i]) {
                paintPlayerInfo(g, i);
            }
        }
    }

    private void paintResult(Graphics g, int posId, int id) {
        if (!isFinishGame) {
            return;
        }
        int x = 0;
        int y = 0;
        switch (posId) {
            case 0:
                x = positionX[posId] + 30;
                y = positionY[posId];
                break;
            case 1:
                x = positionX[posId] - 30;
                y = positionY[posId];
                break;
            case 2:
                x = positionX[posId] + 20;
                y = positionY[posId];
                break;
            case 3:
                x = positionX[posId] + 20;
                y = positionY[posId] + 20;
                break;
        }
        if (resultOrder[id] == 0) {
            g.drawImage(winImage, x, y, 0);
        } else {
            g.drawImage(loseImage, x, y, 0);
        }
    }

    private void paintPlayerInfo(Graphics g, int id) {
        int posId = (id - playerId + maxPlayer) % maxPlayer;
        switch (posId) {
            case 0:
                //avatar
                if (isViewer) {
                    PiPoDesigner.drawString(g, gameData.playerName[id], PiPoDesigner.COLOR_BLACK, PiPoDesigner.COLOR_WHITE, positionX[posId], positionY[posId] - 10);
//                    if (gameData.playerGender[id] == 0) {
//                        g.drawImage(boyAvatarImage, positionX[posId], positionY[posId], 0);
//                    } else {
//                        g.drawImage(girlAvatarImage, positionX[posId], positionY[posId], 0);
//                    }
                    Utils.drawFrame(g, avatarImage, positionX[posId], positionY[posId], gameData.avatarIds[id], gameData.playerGender[id], avatarWidth, avatarHeight);
                    if (isFinishGame) {
                        paintResult(g, posId, id);
                    }
                } else {
                    if (isFinishGame) {
                        //draw result
                        PiPoDesigner.drawString(g, gameData.playerName[id], PiPoDesigner.COLOR_BLACK, PiPoDesigner.COLOR_WHITE, positionX[posId], positionY[posId] - 10);
//                        if (gameData.playerGender[id] == 0) {
//                            g.drawImage(boyAvatarImage, positionX[posId], positionY[posId], 0);
//                        } else {
//                            g.drawImage(girlAvatarImage, positionX[posId], positionY[posId], 0);
//                        }
                        Utils.drawFrame(g, avatarImage, positionX[posId], positionY[posId], gameData.avatarIds[id], gameData.playerGender[id], avatarWidth, avatarHeight);
                        paintResult(g, posId, id);
                    }
                }
                break;
            case 1:
                //name
                PiPoDesigner.drawString(g, gameData.playerName[id], PiPoDesigner.COLOR_BLACK, PiPoDesigner.COLOR_WHITE, positionX[posId], positionY[posId] - 10);
                //avatar
//                if (gameData.playerGender[id] == 0) {
//                    g.drawImage(boyAvatarImage, positionX[posId], positionY[posId], 0);
//                } else {
//                    g.drawImage(girlAvatarImage, positionX[posId], positionY[posId], 0);
//                }
                Utils.drawFrame(g, avatarImage, positionX[posId], positionY[posId], gameData.avatarIds[id], gameData.playerGender[id], avatarWidth, avatarHeight);
                paintResult(g, posId, id);
                break;
            case 2:
                //name
                PiPoDesigner.drawString(g, gameData.playerName[id], PiPoDesigner.COLOR_BLACK, PiPoDesigner.COLOR_WHITE, positionX[posId], positionY[posId] - 10);
                //avatar
//                if (gameData.playerGender[id] == 0) {
//                    g.drawImage(boyAvatarImage, positionX[posId], positionY[posId], 0);
//                } else {
//                    g.drawImage(girlAvatarImage, positionX[posId], positionY[posId], 0);
//                }
                Utils.drawFrame(g, avatarImage, positionX[posId], positionY[posId], gameData.avatarIds[id], gameData.playerGender[id], avatarWidth, avatarHeight);

                paintResult(g, posId, id);
                break;
            case 3:
                //name
                PiPoDesigner.drawString(g, gameData.playerName[id], PiPoDesigner.COLOR_BLACK, PiPoDesigner.COLOR_WHITE, positionX[posId], positionY[posId] - 10);
                //avatar
//                if (gameData.playerGender[id] == 0) {
//                    g.drawImage(boyAvatarImage, positionX[posId], positionY[posId], 0);
//                } else {
//                    g.drawImage(boyAvatarImage, positionX[posId], positionY[posId], 0);
//                }
                Utils.drawFrame(g, avatarImage, positionX[posId], positionY[posId], gameData.avatarIds[id], gameData.playerGender[id], avatarWidth, avatarHeight);
                paintResult(g, posId, id);
                break;
        }
    }

    protected void paintBarMenu(Graphics g) {
        if (isShowChatBox) {
            PiPoDesigner.drawString(g, "Đóng", PiPoDesigner.COLOR_BLACK, PiPoDesigner.COLOR_WHITE, leftScreen + 5, canvasHeight - 20);
            PiPoDesigner.drawString(g, "Xóa", PiPoDesigner.COLOR_BLACK, PiPoDesigner.COLOR_WHITE, canvasWidth - 30, canvasHeight - 20);
            PiPoDesigner.drawString(g, "Gửi", PiPoDesigner.COLOR_BLACK, PiPoDesigner.COLOR_WHITE, canvasWidth / 2 - 20, canvasHeight - 20);

            return;
        } else {
            PiPoDesigner.drawString(g, "Menu", PiPoDesigner.COLOR_BLACK, PiPoDesigner.COLOR_WHITE, leftScreen + 5, canvasHeight - 20);
            if (isShowSubMenu) {
                PiPoDesigner.drawString(g, "Đóng", PiPoDesigner.COLOR_BLACK, PiPoDesigner.COLOR_WHITE, canvasWidth - 30, canvasHeight - 20);
                return;
            }
        }
        if (isViewer) {
            if (!isJoinedGame && isShowJoin) {
                PiPoDesigner.drawString(g, "Tham gia", PiPoDesigner.COLOR_BLACK, PiPoDesigner.COLOR_WHITE, canvasWidth / 2 - 30, canvasHeight - 20);
            }
            if (isFinishGame && isJoinedGame) {
                PiPoDesigner.drawString(g, "Tiếp tục", PiPoDesigner.COLOR_BLACK, PiPoDesigner.COLOR_WHITE, canvasWidth / 2 - 20, canvasHeight - 20);
            }
        } else {
            if (!isFinishGame) {
                if (isBeginGame) {
                    PiPoDesigner.drawString(g, "Mở bài", PiPoDesigner.COLOR_BLACK, PiPoDesigner.COLOR_WHITE, canvasWidth / 2 - 20, canvasHeight - 20);
                }
            } else {
                PiPoDesigner.drawString(g, "Tiếp tục", PiPoDesigner.COLOR_BLACK, PiPoDesigner.COLOR_WHITE, canvasWidth / 2 - 20, canvasHeight - 20);
            }
        }

    }

    private void paintCardInHand(Graphics g) {
        for (int i = 0; i < 3; i++) {
            if (i < cardInHandIndex[0]) {
                cardInHand[0][i].paint(g);
            }
            if (i < cardInHandIndex[1]) {
                cardInHand[1][i].paint(g);
            }
            if (i < cardInHandIndex[2]) {
                cardInHand[2][i].paint(g);
            }
            if (i < cardInHandIndex[3]) {
                cardInHand[3][i].paint(g);
            }
        }
    }
    //--------------------------------------------------------------------------

    void doGameKeyCenter() {
        if (isFinishGame && !isViewer) {
//            Request.finishBacay();
            Request.changeReadyState(0);
            showWaitingRoom();
            return;
        }
        if (isBeginGame) {
            if (startOpen >= 0) {
                Card card = cardInHand[0][startOpen];
                card.openCard();
                int newX = card.getX() - 6;
                if (countOpen == 0) {
                    newX = cardInHand[0][startOpen + 1].getX() - 6;
                }
                card.setPosition(newX, card.getY());
                countOpen++;
            }
            if (countOpen == 2) {
                countOpen = 0;
                Request.openBaCay(playerId, startOpen);
                startOpen--;
                return;
            }
            if (startOpen < 0) {
                cardInHand[0][2].openCard();
                Request.openBaCay(playerId, 2);
                Request.finishOpenCardBaCay();
                isBeginGame = false;
            }
            parent.repaint();
            return;
        }
    }

    private void setCardShare(int[] cardIds) {
        try {
            cardImages = Utils.loadImage("card.png");
        } catch (IOException ex) {
        }
        cardSharePos = new int[maxPlayer];
        startOpen = 1;
        cardHeight = cardImages.getHeight();
        cardWidth = cardImages.getWidth() / 53;
        int playerShareId = cardIds[0];
        int cardIdIndex = 0;
        numberCardReceive = cardIds.length - numberPlayers;
        int countNumberCardShare = 0;
        int centerX = canvasWidth / 2 - cardWidth / 2;
        int centerY = canvasHeight / 2 - cardHeight / 2;
        Debug.d("number player :" + numberPlayers);
        do {
            int cardShareIndex = cardIdIndex + countNumberCardShare / numberPlayers + 1;
            int posId = (playerShareId - playerId + maxPlayer) % maxPlayer;
            cardSharePos[cardMoveIndex % numberPlayers] = posId;
            Debug.d((cardMoveIndex % numberPlayers) + "add pos id :" + posId);
            Card card = null;
//            if (gameData.getMyViewId() < gameData.getMaxPlayer()) {
            card = new Card(cardIds[cardShareIndex], Card.STATE_HIDE, cardImages);
//            } else {
//                card = new Card(cardIds[cardShareIndex], Card.STATE_NORMAL, cardImages);
//            }
            card.initializeMove(centerX, centerY,
                    getDestinationX(posId), getDestinationY(posId), 4);
            cardMoves[cardMoveIndex] = card;
            cardMoveIndex++;
            cardIdIndex += 4;
            cardIdIndex = cardIdIndex % cardIds.length;
            playerShareId = cardIds[cardIdIndex];
            countNumberCardShare++;
        } while (countNumberCardShare < numberCardReceive);
        Debug.d("card move index :" + cardMoveIndex);
    }

    private int getDestinationX(int posId) {
        switch (posId) {
            case 0:
                return positionX[posId] - 20;
            case 1:
                return positionX[posId] - 30;
            case 2:
                return positionX[posId] - 50;
            case 3:
                return positionX[posId];
        }
        return 0;
    }

    private int getDestinationY(int posId) {
        switch (posId) {
            case 0:
                return positionY[posId];
            case 1:
                return positionY[posId] - 30;
            case 2:
                return positionY[posId];
            case 3:
                return positionY[posId] - 30;
        }
        return 0;
    }

    public void processMessage(String[] part) {
        super.processMessage(part);
        if (part[0].equals("SE")) {
            isLoading = false;
            gameData.setNumberPlayerInTable(part);
            showChooseTable();
            isGoBack = true;
            parent.repaint();
            return;
        }
        if (part[0].equals("UPAS")) {
            gameData.setTablePass(part);
            return;
        }
        if (part[0].equals("OB")) {
            int posId = (Integer.parseInt(part[1]) - playerId + maxPlayer) % maxPlayer;
            int cardOrder = Integer.parseInt(part[2]);
            if (cardInHand[posId][cardOrder] != null) {
                cardInHand[posId][cardOrder].openCard();
                parent.repaint();
            }
            return;
        }
        if (part[0].equals("USE")) {
            gameData.setNumberPlayerInTable(part);
            return;
        }
        if (part[0].equals("SM")) {
            gameData.setTableMoneyBet(part);
            return;
        }
        if (part[0].equals("RO")) {
            gameData.setRoArrData(part);
            if (numberPlayers == 1) {
                isFinishGame = true;
                isDrawResult = true;
            }
            parent.repaint();
            return;
        }
        if (part[0].equals("MO")) {
            gameData.setMoArrData(part);
            parent.repaint();
        }
        if (part[0].equals("RE")) {
            gameData.setReArrData(part);
            isLoading = false;
            Debug.d("isViewer :" + isViewer);
            Debug.d("is joined :" + isJoined);
            if (!isViewer && (isJoined || isShowJoin)) {
                showWaitingRoom();
                isGoBack = true;
            }
            if (isViewer && !isJoined) {
                resetGameForView();
            }
            return;
        }
        if (part[0].equals("CM")) {
            int money = Integer.parseInt(part[2]);
            int id = Integer.parseInt(part[1]);
            int posId = (id - playerId + maxPlayer) % maxPlayer;
            gameData.changeMoney(id, money);
            switchMoneyChange(posId, part[2]);
            //  startTimeChat[posId] = System.currentTimeMillis();
            parent.repaint();
            return;
        }
        if (part[0].equals("INFO")) {
            gameData.setInfoData(part);
            return;
        }
        if (part[0].equals("S3C") && isViewer) {
            cardInHandId = new int[part.length - 1];
            for (int i = 0, l = cardInHandId.length; i < l; i++) {
                cardInHandId[i] = Integer.parseInt(part[i + 1]);
            }
            setCardShare(cardInHandId);
            return;
        }
        if (part[0].equals("RS3")) {
            processData(part);
            return;
        }
        if (part[0].equals("JS")) {
            int joinResult = Integer.parseInt(part[1]);
            if (joinResult == 0) {
                isLoading = false;
                dialogString = "Bàn đã đủ người chơi";
                isJoined = false;

            } else {
                isJoined = true;
                isLoading = false;
                dialogString = "Bạn sẽ tham gia ở ván sau";
            }
            isShowJoin = false;
            parent.repaint();
            return;
        }
        if (part[0].equals("CHAT")) {
            int postId = (Integer.parseInt(part[2]) - playerId + maxPlayer) % maxPlayer;
            if (postId != 0) {
                switchMessengerBox(postId, part[1]);
                parent.repaint();
            }
            return;
        }
    }

    private void resetGameForView() {
        cardMoveIndex = 0;
        for (int i = 0; i < numberPlayers; i++) {
            cardInHandIndex[i] = 0;
        }
        numberCardShared = 0;
        isFinishGame = false;
        parent.repaint();
    }

    protected void doGameSoftKeyLeft() {
    }

    protected void doGameSoftKeyRight() {
    }

    public void doKeyLeft() {
    }

    public void doKeyRight() {
    }
}
